<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * App\Models\PollWorks
 *
 * @property integer $id
 * @property integer $works_id
 * @property integer $poll_id
 * @property integer $score
 * @property integer $prize_id
 * @method static \Illuminate\Database\Query\Builder|\App\Models\PollWorks whereId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\PollWorks whereWorksId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\PollWorks wherePollId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\PollWorks whereScore($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\PollWorks wherePrizeId($value)
 * @mixin \Eloquent
 * @property-read \App\Models\Works $works
 * @property-read \App\Models\Poll $poll
 */
class PollWorks extends Model
{
    protected $table = 'poll_works';

    public $timestamps = false;

    public $fillable = [
        'prize_id'
    ];

    public function works()
    {
        return $this->belongsTo(Works::class, 'works_id');
    }

    public function poll()
    {
        return $this->belongsTo(Poll::class, 'poll_id');
    }

    public function vote(Poll $poll)
    {
        $result = [
            'status' => false,
            'msg'    => '非法操作.',
        ];

        //检查用户权限
        if ($poll->only_user && !\Auth::check()) {
            $result['msg'] = '请登录后进行操作.';
            return $result;
        }

        try {
            $this->score++;
            $this->save();
            PollLog::create([
                'poll_works_id' => $this->id,
                'poll_id'       => $this->id,
                'works_id'      => $this->works_id,
                'ip'            => request()->ip(),
                'user_id'       => \Auth::id() ? \Auth::id() : 0,
            ]);
            $result = [
                'status' => true,
            ];
            return $result;
        } catch (\Exception $e) {
            $result['msg'] = '系统出错.';
            return $result;
        }
    }

    public function prize()
    {
        return $this->belongsTo(PollPrize::class, 'prize_id');
    }
}